#coding:utf-8
from lovewith.utils.mtcache import MtCache
from lovewith.utils.tools import my_iterator
from lovewith.share.models import AttachLike
from lovewith.share.views.modules.attach_flag import AttachFlagApi


class AttachLikeApi:
    def __init__(self):
        pass

    #根据image_id获取like总数
    @staticmethod
    def get_total_by_image(image_id, user_id=None):
        if not user_id:
            return AttachLike.objects.filter(post_image_id=image_id).count()
        else:
            return AttachLike.objects.filter(user_id=int(user_id), post_image_id=image_id).count()

    #get total by uid
    @staticmethod
    def get_total_by_user(user_id):
        return AttachLike.objects.filter(user_id=int(user_id)).count()

    #get user like by uid
    @staticmethod
    def get_by_user(user_id, start, last):
        like_data = []
        image_like = AttachLike.objects.filter(post_image__share_post__is_delete=False, user_id=int(user_id)).order_by('-id')[start: last]
        for img in my_iterator(image_like):
            #tk数据
            img_sale_data = AttachFlagApi.get_goods_by_image(img.post_image.id)
            if img_sale_data:
                img_sale_data = img_sale_data[0]
            else:
                img_sale_data = None

            like_data.append({
                'title': img.post_image.share_post.title,
                'uid': img.post_image.share_post.user.id,
                'name': img.post_image.share_post.user.username,
                'avatar': img.post_image.share_post.user.avatar,
                'cover': img.post_image.path,
                'share_id': img.post_image.share_post.id,
                'cover_id': img.post_image.id,
                'sale_data': img_sale_data,
                'is_video': img.post_image.share_post.is_video,
                'video': img.post_image.share_post.video
            })

        return like_data

    #批量添加like
    def add_to_image(self, image_datas, user):
        new_like = []
        for img in image_datas:
            total_like = self.get_total_by_image(img.id, user.id)
            if total_like == 0:
                new_like.append(
                    AttachLike(post_image=img, user=user)
                )

        MtCache('user_like').delete(user_id=user.id, page=1)

        AttachLike.objects.bulk_create(new_like)


    #删除图片的喜欢
    @staticmethod
    def remove_as_image(image_data, user):
        #判断图片是否存在
        like_filter_data = AttachLike.objects.filter(post_image=image_data, user_id=user.id)
        for like in like_filter_data:
            MtCache('user_like').delete(user_id=like.user_id, page=1)
        like_filter_data.delete()


    #删除
    @staticmethod
    def delete_by_image(image_id):
        like_data = AttachLike.objects.filter(post_image_id=image_id)
        like_data.delete()